//app.js注册小程序App()函数
var http = require('service/http.js');
var util = require('utils/util.js'); //工具类
var checkShopInfoTask = '';
App({
  data: { //全局数据
    //-------------------安全域名-----------------
    baseUrl: 'https://wx.mamatx.com.cn',// 'http://20d6z36665.51mypc.cn', //   ////'https://www.momjoin.com.cn', //  
    version: '1.7.8', //本地版本号
    versionUpdate: false, //版本更新
    guideAttention:'',//是否显示引导关注
    cityName: '', //程序内默认city
    cityArray: [], //全部城市
    isShowAD: 'notYet', //是否展示首页的投放广告
    adDetailArr: [], //广告信息
    adInterval: '', //每张广告投放时间间隔
    showPage: false, //是否展示页面
    countAdTime: '', //广告计时时间
    scrollViewHeight: 0, //滚动窗口高度
    //-----------商品加载分页参数page-----------------
    pageNo: 1,
    pageSize: 10, //分页商品条数
    itemList: [], //按条件查询商品列表
    itemTotal: '', //商品列表总分页页数

    //----------------用户登录初始化-------------------
    loginCode: '', //用于登录获取的code,5分钟之内有效
    codeExpiryTime: 300000, //code过期时间
    loginType: 0, //登录入口，从公众号进入
    isAuthorization: 'notYet', //是否授权登陆
    hasGotShopInfo: 'notYet', //已经获取到店铺信息
    loginMsg: '', //用于登录检查过期SessionTimeOut
    userInfoScope: false, //用户授权状态

    personOrderInfo: '', //订单信息
    pesonalCartInfo: '', //购物车数量
    customerServicePhone: '', //客服电话

    showLogin: 'notYet', //是否展示登录
    isBindPhone: false, //是否已经绑定手机
    showLoadding: true, //加载动画gif

    //--------------------默认商品图片-----------------
    defaultImgUrl: 'https://momjoin.com/order/carouselImgs/default_img.jpg',
    isshow: false,
    opMask: 0,
    toBuy: false,
    skuid: '', //skuid(加入购物和结算使用)
    //----加入购物车动画---------------------

    animationData: '', //所有动画
    skuTitles: '',
    maskHeight: '', //mask高度
    minPrice: 0, //最小价格（初始化商品价格范围）
    maxPrice: 0, //最大价格
    skus: [], //所有sku内容
    distAttrs: [], //不重复的可选属性值
    chooseAttrids: [], //已选属性id
    getStock: '', //是否请求到库存

    isLimited: false, //是否为限购商品
    limitedNum: 0, //限购数量

    //----------暂存购物车商品信息-------------------
    itemId: '', //暂存购物车商品id 
    skuId: '', //skuid
    count: 1, //购物车数量
    stock: 0, //默认库存
    cartStock: 0, //用户显示购物车剩余库存
    cartProducts: [], //购物车列表
    //--------分享商品动画------------------------------

    shareImgUrl: '', //分享图片地址
    showCanvas: false, //用于生成图片
    windowWidth: 0, //可视窗口大小
    windowHeight: 0,
    codeUrl: '', //分享码地址

    //-----------判断是否下单----------------------------
    ispay: false, //是否点击支付
    //-----------按条件搜索返回商品列表----------
    searchList: [],
    inputFocus: false, //是否聚焦
    //-----------购物车商品数量----------------------
    cartCount: '',
    addcart: false, //是否通过验证可以加入购物车(购物车sku验证)

    //----------商品分享分享人inviter-店铺id------------------------------
    inviter: '', //分享人inviter(通过二维码扫描进入小程序获取)
    shopuid: '', //店铺id
    shopName: '', //店铺名称
    hasShop: false, //自己是否已经拥有分销店铺
    isOwnShop: '', //是否为自己的店铺：1---自己的店铺；0--别人的店铺；null---平台

    //------------   分享妈妈中心页面展示数据---------------------
    personalInviteInfo: {}, //用户分享相关信息（订单＼用户）
    zjuserfxfee: 0, //累计收益

    //分销店铺分享商品，支付后回到分销店铺标识
    userName: '', //用户真实姓名用于用户提现
    hasRealName: false, //用户是否绑定真实姓名

    //------------优惠券-----------------------------------------
    discountCardList: [], //优惠券列表
    //------------------打开设置-------------------------------------
    showSettingBox: false, //打开引导用户设置弹出层
    //-------------------formIdPool池 用于消息推送--------------------
    formIdPool: [], //用于模板消息推送
    //----其他-----
    pageName: 'home', //当前页名称-
    shopInfoTimeOut: false, //店铺信息是否过期
    shopInfoExTime: 600000, //店铺信息过期时间
    //---登录后有无优惠券---
    hasShopCoupon: '', //登录后有无优惠券
    hasCouponInfo: '', //结算时根据订单金额查看有无可用优惠券
    couponInfo: '', //优惠券信息
    selectCoupon: '', //已选择的优惠券信息
    couponCount: '', //优惠券数量

    //自定义消息
    productLevMsgs: '', //商品留言[]
    msgImgObj: {}, //需要上传图片的留言项
    //团队阶级id
    zjGroupLevelId: '', //zjGroupLevelId
    zjGroupActivityId: '', //参与拼团的活动id

    // 登录code
    loginCode: '',

    // sku折扣以及限购数量
    skuDeprnRatio: '', //sku折扣
    // 显示引导'添加到我的小程序'
    showCollectionTip: '',
  },
  globalData: {
    userInfo: null,
    products: [], //所有商品列表
    product: {}, //当前正在浏览的商品
  },
  onLaunch: function(option) { //监听小程序初始化，全局只运行一次
    console.log("onLaunch进入appjs监听小程序初始化，全局只运行一次", option)
    this.getGuideType(option.scene);

    //获取登录code
    // this.getLoginCode();
``
    //清除本地缓存信息
    this.removeLocalStorage();

    //隐藏底部菜单
    wx.hideTabBar();

    //获取广告轮播
    this.getAdvers();

    //获取城市列表
    this.loadCityArray();

    //滚动窗口高度
    this.getViewHeight();

    //获取用户订单、购物车数量
    this.checkCartCount();

    //显示添加到我的小程序
    this.showCollectionTip();


  },
  /**
   * 获取登录code
   */
  getLoginCode: function() {
    wx.login({
      success: (res) => {
        console.log('wx.login', res.code);
        this.data.loginCode = res.code;
      },
      fail: (res) => {
        console.log('获取登录code失败' + res);
      }
    })
  },
  // }, 290000)
  /**
   * 获取引导关注类型
   */
  getGuideType: function(scene) {
    if (scene == '1011' || scene == '1047' || scene == '1089' || scene == '1038') {
      console.log('getGuideType-可展示引导关注公众号组件');
      this.data.guideAttention = true;
    }
  },

  onShow: function() { //checksession (从后台进入小程序前台) 更改全局data变量
    console.log('app-Onshow');


    clearTimeout(checkShopInfoTask); //清除店铺信息任务

    //监听小程序版本更新--清除本地店铺信息
    this.checkVersion();

    //清除formIdPool
    this.data.formIdPool = [];
  },


  //获取广告轮播
  getAdvers: function() {

    let that = this;

    http.getReq('/weixin/zjCarouseImg/advers', {}, function(res) {
      console.log('广告advers', res);

      let [adDetailArr, adInterval, countAdTime, isShowAD, showAdTime] = [that.data.adDetailArr, that.data.adDetailArr, that.data.countAdTime, that.data.isShowAD, that.data.showAdTime];
      adDetailArr = res.zjAdvertImgArr; //广告信息
      if (adDetailArr.length > 0) {
        adInterval = res.interval; //时间间隔
        countAdTime = parseInt(adInterval) * adDetailArr.length; //总时长
        isShowAD = true;
      } else {
        isShowAD = false;
        countAdTime = 0;
      }
      that.data.adDetailArr = adDetailArr;
      that.data.adInterval = adInterval;
      that.data.countAdTime = countAdTime;
      that.data.isShowAD = isShowAD;
      that.data.shopInfoExTime = parseInt(res.shopInfoExTime) * 60000; //shopinfo过期时间
      console.log('countAdTime--' + countAdTime);
    });

  },

  getViewHeight: function() { //滚动窗口高度
    var res = wx.getSystemInfoSync(); //系统参数
    let [windowWidth, windowHeight] = [res.windowWidth, res.windowHeight];
    let scrollViewHeight = res.windowHeight * 2;
    this.data.scrollViewHeight = scrollViewHeight; //滚动窗口高度
    this.data.windowWidth = windowWidth; //窗口高度
    this.data.windowHeight = windowHeight; //窗口高度
  },
  removeLocalStorage: function() { //清除本地缓存信息
    console.log('清除店铺信息');
    //初始化本地登录信息
    this.data.isAuthorization = 'notYet'; //是否授权登陆
    this.data.isShowAD = 'notYet'; //是否授权登陆
    this.data.showLogin = 'notYet'; //是否授权登陆
    this.data.hasShopCoupon = ''; //初始化优惠券信息
    
    let shopInfo = wx.getStorageSync('shopInfo');
    

    if ((shopInfo.isOwnShop || '') !== '1') {
      //清除店铺之前店铺信息
      wx.removeStorageSync('shopInfo');
    }
    //清除地理位置，重新获取
    wx.removeStorageSync('cityName');
  },

  onHide: function() {

    //清空广告数据
    this.removeAdMessage();

    //保存formid
    this.saveFormIdPool();

    this.data.hasGotShopInfo = 'notYet';

    this.data.isFollowChat = ''; //初始化关注公众号数据

    //清除分享店铺信息
    this.clearShopInfo();

  },

  removeAdMessage: function() { //清空广告数据

    this.data.adDetailArr = [];
    this.data.adInterval = ''; //时长间隔
    this.data.countAdTime = ''; //计时时间
    this.data.isShowAD = false; //是否展示广告

  },


  checkVersion: function() { //检查本地版本号更新
    //---------------------检查本地版本号------------------------------
    let [newVersion, version] = [this.data.version, wx.getStorageSync('version')];
    console.log('版本号是否一致：' + (newVersion == version));
    if (newVersion !== version) {
      //更新本地数据
      wx.setStorageSync("version", newVersion);
      this.data.versionUpdate = true;
    }
    console.log('最新版本号：' + newVersion + '；本地版本号：' + version + '；更新后版本号：' + wx.getStorageSync('version'));
  },

  //---------------------检查session 是否过期---------
  checkSession: function(shopuid, inviter, shareKey = '') {

    let that = this;
    that.data.isAuthorization = 'notYet'; //初始化登录信息

    //获取本地session、本地店铺信息、分享标识
    let rdSession = wx.getStorageSync('rd_session');
    console.log("appjs:checksession:" + rdSession);

    let shopInfoTimeOut = that.data.shopInfoTimeOut; //查看店铺信息是否过期
    // pageData = shopInfoTimeOut ? '' : pageData; //店铺过期清理 单个页面请求分享数据
    console.log('app-checkSession', shopInfoTimeOut, shopuid, inviter);
    // 有分享数据--更新shopuid
    shopuid = shopInfoTimeOut ? '' : (shopuid ? shopuid : that.data.shopuid);
    inviter = shopInfoTimeOut ? '' : (inviter ? inviter : that.data.inviter);
    // let shopuid = pageData ? pageData.data.shopuid : that.data.shopuid;
    // let inviter = pageData ? pageData.data.inviter : that.data.inviter;

    //请求获取isAuthorization授权状态存储店铺信息
    http.getReq('/weixin/checkSession', {
      'rdSession': rdSession
    }, function(res) {

      console.log('checkSession返回信息:', res);
      let shopInfo = {};
      that.data.loginMsg = res.msg;
      if (res.ret) { //已授权 未过期

        if (res.data.isOwnShop == '1') { //自己有店
          //本地存储店铺信息:店铺id、店铺名称、是否有分销店铺
          shopInfo.shopuid = res.data.shopuid;
          shopInfo.shopName = res.data.shopName;
          shopInfo.isOwnShop = res.data.isOwnShop;
          wx.setStorageSync('shopInfo', shopInfo);
          that.data.hasGotShopInfo = true;
        } else { //自己没有店铺
          console.log('自己没有店铺shopuid', shopuid);
          if (shopuid != '') { //有分享店铺信息
            that.getShareShopInfo(shopuid, inviter); //根据分享信息查询店铺
          } else { //没有分享人店铺显示首次关注店铺
            //本地存储店铺信息:店铺id、店铺名称、是否有分销店铺
            shopInfo.shopuid = res.data.shopuid;
            shopInfo.shopName = res.data.shopName;
            shopInfo.isOwnShop = res.data.isOwnShop;
            wx.setStorageSync('shopInfo', shopInfo);
            that.data.hasGotShopInfo = true;
          }
        }
        //更新本地缓存店铺信息
        wx.setStorageSync("vip", res.data.mLevel == 'vip' ? true : false);

        console.log('已授权不用登陆isAuthorization：true');
        that.data.isAuthorization = true;
        that.data.inviter = inviter || '';
        that.data.shopuid = shopuid || '';
        that.data.shopInfoTimeOut = false; //初始化店铺信息过期时间
        //检查有无店铺优惠券(扫小程序码进入)
        that.checkShopCoupon(shareKey, rdSession);

      } else { //未授权 
        that.data.isAuthorization = false;
        return;
      }

    });
  },


  //用户登录
  userLogin: function(e, shopuid, inviter, shareKey = '') {

    let shopInfoTimeOut = this.data.shopInfoTimeOut; //查看店铺信息是否过期

    //有分享数据--更新shopuid
    shopuid = shopInfoTimeOut ? '' : (shopuid ? shopuid : this.data.shopuid);
    inviter = shopInfoTimeOut ? '' : (inviter ? inviter : this.data.inviter);

    //空字符串拦截
    shopuid = (shopuid == "''" ? '' : shopuid);

    let [userInfo, iv, encryptedData] = [e.detail.userInfo, e.detail.iv, e.detail.encryptedData];
    let code = this.data.loginCode;
    http.getReq('/weixin/wxUser/login', {
      code: code,
      userInfo: userInfo, //用户信息
      encryptedData: encryptedData, //用户敏感信息
      iv: iv, //加密算法的初始向量,
      shopuid: shopuid, //绑定首次关注使用
      shareKey: '', //分享标识（无用，误删）
    }, (loginData) => {

      console.log('loginData登录返回信息:', loginData);

      let shopInfo = {}; //本地店铺信息

      if (loginData.ret) { //登录成功     
        //自己有店、不是分享店铺 且有绑定关系
        if (loginData.data.isOwnShop === '1') { //自己有店铺
          shopInfo.shopuid = loginData.data.shopuid;
          shopInfo.shopName = loginData.data.shopName;
          shopInfo.isOwnShop = loginData.data.isOwnShop;
          wx.setStorageSync('shopInfo', shopInfo); //更新本地缓存店铺信息
          this.data.hasGotShopInfo = true;
        } else { //自己没有店铺
          if (shopuid != '') { //有分享店铺信息
            this.getShareShopInfo(shopuid, inviter); //根据分享信息查询店铺
          } else { //没有分享人店铺显示首次关注店铺
            shopInfo.shopuid = loginData.data.shopuid;
            shopInfo.shopName = loginData.data.shopName;
            shopInfo.isOwnShop = loginData.data.isOwnShop;
            wx.setStorageSync('shopInfo', shopInfo); //更新本地缓存店铺信息
            this.data.hasGotShopInfo = true;
          }
        }

        console.log('登录后显示店铺信息：', wx.getStorageSync('shopInfo')); //缓存用户信息到本地
        wx.setStorageSync('userInfo', userInfo); //用户信息保存到本地
        wx.setStorageSync('unionid', loginData.data.unionid)
        wx.setStorageSync('isBindPhone', loginData.data.hasPhoneNum)
        wx.setStorageSync("rd_session", loginData.data.rd_session);
        wx.setStorageSync("expiration", loginData.data.expiration); //过期时间
        wx.setStorageSync("vip", loginData.data.mLevel == 'vip' ? true : false);
        //更新appjs全局变量
        this.globalData.userInfo = userInfo;
        this.data.showLogin = false; //隐藏登录界面
        this.data.loginMsg = ''; //用于登录检查过期SessionTimeOut
        this.data.inviter = inviter || '';
        this.data.shopuid = shopuid || '';
        this.data.shopInfoTimeOut = false; //初始化店铺信息过期时间
        this.data.isAuthorization = true;

        this.connectionTimeout('授权登录成功');
        this.getDiscountCard(); //获取优惠券数量
        //检查有无店铺优惠券(扫小程序码进入)
        this.checkShopCoupon(shareKey, loginData.data.rd_session);
      }
    });

  },

  //------------------显示购物车、订单等数量----------------------
  getElementsCounts: function() {
    
    let that = this;
    let getElementCountTask = setInterval(() => {
      let rdSession = wx.getStorageSync('rd_session');
      let isAuthorization = that.data.isAuthorization;
      if (isAuthorization === true) {
        clearInterval(getElementCountTask);
        http.getReq('/weixin/personal/getElementsCounts', {
          'rdSession': rdSession
        }, function(res) {
          console.log('getElementsCounts:', res);
          if (res.ret) {

            let cartCount = res.data.pesonalCartInfo.count; //购物车数量
            that.data.cartCount = cartCount; //购物车数量
            wx.setStorageSync('cartCount', cartCount); //购物车数量
            that.checkCartCount(); //显示购物车红点

            that.data.personOrderInfo = res.data.personOrderInfo; //用户订单信息
            that.data.pesonalCartInfo = res.data.pesonalCartInfo; //用户购物车信息
            that.data.personalInviteInfo = res.data.personalInviteInfo; //用户分享相关信息（订单＼用户）
            that.data.zjuserfxfee = res.data.zjuserfxfee; //用户累计收益
            that.data.customerServicePhone = res.data.customerServicePhone; //客服电话
            that.data.couponCount = res.data.couponCount; //优惠券数量

          }
        });
      }
    }, 300)
  },

  checkCartCount: function() {
    let cartCount = wx.getStorageSync('cartCount') || this.data.cartCount;
    if (cartCount === '') { //本地没有购物车数据
      this.getElementsCounts();
    } else {
      if (cartCount > 0) { //购物车项显示红点
        wx.showTabBarRedDot({
          index: 1
        })
      } else { //购物车项隐藏红点
        wx.hideTabBarRedDot({
          index: 1
        })
      }
    }
  },
  //-------登陆初始化动画--------------
  loginAnimation: function() {
    wx.hideTabBar();
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease',
      delay: 0
    })
    this.getLoginCode(); //获取code
    this.animation = animation;
    animation.height('100%').opacity(1).step();
    this.data.animationData = animation.export();
    this.data.showLogin = true;
  },

  getToBuy: function(e) { //是否立即购买
    // 判断是否有商品下标(商品列表)
    let that = this;
    //let pindex = event.currentTarget.dataset.pindex;//商品列表下标
    let addtype = e.currentTarget.dataset.type || 'submit'; //判断是否是加入购物车
    let toBuy = false;
    ////判断是加入购物车还是立即购买---  ----设置按钮状态
    if (addtype == 'add') {
      toBuy = false;
    } else {
      toBuy = true;
    }
    that.data.toBuy = toBuy;
  },
  //--------------点击购物车按钮弹窗（加载商品和购买动作）---------------------------------
  addmessage: function() { //加入购物 车并选择购买商品信息

    //初始化商品变量
    this.data.itemId = '';
    this.data.skuId = '';
    this.data.count = 1;
    this.data.stock = 0;
    this.data.itemPrice = '';
    this.data.limitedNum = ''; //商品库存
    this.data.skuDeprnRatio = ''; //商品折扣
    this.data.getStock = ''; //初始化查询库存状态
    //appjs中的初始化数据赋值------------------------------------
    this.data.chooseAttrids = []; //置空被选中的属性
  },
  //获取商品库存
  getStock: function(that) {
    let appThis = this;
    let product = that.data.product;
    let productId = product.id;
    console.log('zjGroupLevelId', that.data.zjGroupLevelId);
    //----------------------------更新总库存和sku----------------------------

    let data = {
      'productId': productId,
      'zjGroupLevelId': that.data.zjGroupLevelId || ''
    }; //请求参数

    http.getReq('/weixin/item/getStock', data, function(res) {
      console.log('getStock', res);
      appThis.data.cartStock = res.stock; //购物车数量
      product.stock = res.stock; //商品总库存
      if (res.skus != null) { //商品sku库存
        product.skus = res.skus;
      } else {
        product.skus = [];
      }
      appThis.data.product = product; //购物车数量
      appThis.data.getStock = true; //已刷新库存标识
      console.log('刷新后库存stock--' + product.stock);
    });
  },

  getSkuValue: function(product) { //获取商品sku
    // console.log('获取商品sku-getSkuValue', product);

    let skus = product.skus;
    let prices = [];
    let skuAttrsObjs = [];
    let distAttrs = [] //所有分组展示信息[{name:"",value:[{},{}]},{name:"",value:[{},{}]}]    
    let skuTitles = [];
    let appThis = this;

    //--------判断有无skus----------------------------------------------
    if (skus.length > 0) {
      //取出所有属性值-----------------------------------------------------
      for (let i = 0; i < skus.length; i++) {
        prices.push(skus[i].price);
        let skuAttrs = skus[i].skuAttrs;
        if (skuAttrs.length >= 1) {
          for (let j = 0; j < skuAttrs.length; j++) {
            let attrObj = skuAttrs[j]
            skuAttrsObjs.push(attrObj); //将所有attrs取出
          }
        }
      }
      console.log(skuAttrsObjs);
      //skuAttrsObjs分组-----------属性分组[{name:"",value:[{},{}]},{name:"",value:[{},{}]}] 
      //name 对应 attrTitle value对应属性值

      let distAttrObj = {} //分组对象 distAttrObj.name='' distAttrObj.value[]
      distAttrObj.value = [] //存属性值信息
      let zcAttr = {} //暂存属性值 distAttrObj.value[]中对象包括 id 、attrValue、statu
      let names = ""; //存储name 数组

      if (skuAttrsObjs.length > 0) { //sku长度 > 0
        //第一次存储distAttrs数据
        distAttrObj.name = skuAttrsObjs[0].attrTitle; //分组标题
        distAttrObj.hasSelect = false; //同级是否已经有被选的选项
        zcAttr.id = skuAttrsObjs[0].id; //id （需要传递的值）
        zcAttr.attrValue = skuAttrsObjs[0].attrValue; //attrValue（展示的值）
        zcAttr.statu = 1; //状态
        distAttrObj.value.push(zcAttr);
        distAttrs.push(distAttrObj);
        names = distAttrs[0].name;

        for (let j = 0; j < distAttrs.length; j++) {
          console.log("distAttrs.length:" + distAttrs.length)
          for (let i = 1; i < skuAttrsObjs.length; i++) { //skuAttrsObjs从第一个开始
            if (skuAttrsObjs[i].attrTitle != distAttrs[j].name && names.lastIndexOf(skuAttrsObjs[i].attrTitle) < 0) { //属性名和name数组不包含属性名，distAttrs添加
              //初始化存储属性-----------------------------------------------------------------
              let distAttrObj1 = {} //分组对象 distAttrObj.name='' distAttrObj.value[]
              distAttrObj1.value = [] //存属性值信息
              let zcAttr1 = {} //暂存属性值 distAttrObj.value[]中对象包括 id 、attrValue、statu
              distAttrObj1.value = []; //初始化--存放不同的sku属性
              //-----------------------添加分组信息--------------------------------------------
              distAttrObj1.name = skuAttrsObjs[i].attrTitle;
              distAttrObj1.hasSelect = false; //同级是否已经有被选的选项
              zcAttr1.id = skuAttrsObjs[i].id;
              zcAttr1.attrValue = skuAttrsObjs[i].attrValue; //attrValue（展示的值）
              zcAttr1.statu = 1; //状态
              distAttrObj1.value.push(zcAttr1);
              distAttrs.push(distAttrObj1);

            } else { //名称相等比对value[]中的id
              let zcAttr2 = {} //暂存属性值 distAttrObj.value[]中对象包括 id 、attrValue、statu
              for (let s = 0; s < distAttrs.length; s++) {
                if (distAttrs[s].name == skuAttrsObjs[i].attrTitle) { //循环对比，若属性标题（时间等）
                  let distAttrsValues = distAttrs[s].value;
                  let add = true;
                  for (let v = 0; v < distAttrsValues.length; v++) { //对比属性值id
                    if (skuAttrsObjs[i].id == distAttrsValues[v].id) { //若相等则不添加
                      add = false;
                    }
                  }
                  if (add) { //添加distAttrs 属性中的value
                    zcAttr2.id = skuAttrsObjs[i].id;
                    zcAttr2.attrValue = skuAttrsObjs[i].attrValue; //attrValue（展示的值）
                    zcAttr2.statu = 1; //状态
                    distAttrs[s].value.push(zcAttr2);
                  }
                  break;
                }
              }
            }
            for (let n = 0; n < distAttrs.length; n++) {
              if (names.lastIndexOf(distAttrs[n].name) < 0) {
                names = names + "," + distAttrs[n].name;
              }
            }
          }
        }
      }
    }
    // console.log("最终得到：" + distAttrs.length);
    if (distAttrs.length == 1) {
      console.log('sku属性长度为1');
      let attrValues = distAttrs[0].value;
      for (let a = 0; a < attrValues.length; a++) {
        for (let s = 0; s < skus.length; s++) {
          if (attrValues[a].id == skus[s].attrListIds && skus[s].stock < 1) { //库存小于1 改变其属性状态值
            attrValues[a].statu = 0;
          }
        }
      }
      distAttrs[0].value = attrValues;
    }
    appThis.data.skus = skus;
    appThis.data.skuTitles = skuTitles;
    appThis.data.distAttrs = distAttrs;
    appThis.data.stock = product.stock
    //--------------6.20修改部分
    // console.log(distAttrs);
    //最终得到的distAttrs 中的sku长度，长度为1时设为默认
    for (let d = 0; d < distAttrs.length; d++) {
      if (distAttrs[d].value.length == 1) {
        distAttrs[d].value[0];
        let valObj = {};
        valObj.haveUnionSku = true; //属性下标
        valObj.attrindex = d; //属性下标
        valObj.itemindex = 0; //属性值下标
        valObj.val = distAttrs[d].value[0].id; //属性值id
        appThis.selectValue(valObj); //默认点击选中该属性
      }
    }
    //--------------6.20修改部分
    console.log("product.stock:" + product.stock);
  },
  unAddMessage: function() { //取消添加商品信息
    this.data.isshow = false;
    // this.data.opMask = 0;
    //-------------初始化数据---------------------------
    this.data.skus = [];
    this.data.distAttrs = [];
    this.data.chooseAttrids = [];
    this.data.itemId = '';
    this.data.skuId = '';
    this.data.count = 1;
    this.data.stock = 0;
    this.data.itemPrice = ''; //商品显示价格
    this.data.itemImg = ''; //商品显示价格
    this.data.getStock = ''; //以获取库存信息
  },
  //---------------------------点击选择商品属性---------------------------------
  selectValue: function(e) {
    console.log(e);
    let [attrindex, itemindex, val] = ['', '', ''];
    if (e.haveUnionSku) { //具有唯一sku默认选中
      attrindex = e.attrindex; //属性下标
      itemindex = e.itemindex; //属性值下标
      val = e.val; //属性值id
    } else {
      attrindex = e.currentTarget.dataset.attrindex; //属性下标
      itemindex = e.currentTarget.dataset.itemindex; //属性值下标
      val = e.currentTarget.dataset.val; //属性值id
    }
    //获取已选节点
    let chooseAttrids = this.data.chooseAttrids;
    console.log("已选择chooseAttrids--" + chooseAttrids);
    //判断是否已被选中--更改选中状态-----------------------------
    /**
     * 属性分组distAttrs
     */
    let distAttrs = this.data.distAttrs;
    let attrValues = distAttrs[attrindex].value;
    if (attrValues[itemindex].statu == 2) { //已选中
      attrValues[itemindex].statu = 1
      distAttrs[attrindex].hasSelect = false; //取消被选状态
      chooseAttrids[attrindex] = ''; //备选状态置空

    } else { //未选中
      distAttrs[attrindex].hasSelect = true; //该级别改变选中状态
      chooseAttrids[attrindex] = val; //加入已选属性数组
      for (let d = 0; d < attrValues.length; d++) { //更改其他级别属性
        if (d == itemindex) {
          attrValues[d].statu = 2
        } else {
          attrValues[d].statu = 1
        }
      }
    }
    distAttrs[attrindex].value = attrValues;
    this.data.chooseAttrids = chooseAttrids;
    //---------------- step 1  设置为选择属性中不可选节点状态------------------------

    let all_ids = this.filterAttrs(chooseAttrids); //符合条件的所有属性值
    /**
     * 未选择的属性组other_notsel_attr(结构同distAttrs)
     */
    let other_notsel_attr = []; //所有未选属性
    /**
     * 所有已选规格属性sel_goods_attr(结构同distAttrs)
     */
    let sel_goods_attr = []; //所有已选规格属性

    for (let i = 0; i < distAttrs.length; i++) {
      if (distAttrs[i].hasSelect) { //已选
        sel_goods_attr.push(distAttrs[i]);
        continue;
      } else {
        other_notsel_attr.push(distAttrs[i]);
      }
    }

    //设置未选属性可选状态
    for (let j = 0; j < other_notsel_attr.length; j++) {
      let attrValue = this.setBlock(other_notsel_attr[j], all_ids); //选择属性中的不可选节点
      other_notsel_attr[j].value = attrValue;
    }
    // console.log('未选属性状态值');
    // console.log(other_notsel_attr);
    //------------step 2 设置已选节点的同级节点是否可选---------------------------

    for (let s = 0; s < sel_goods_attr.length; s++) {
      let attrValue2 = this.update_2(sel_goods_attr[s]);
      sel_goods_attr[s].value = attrValue2;
    }
    // console.log('已选属性状态值');
    // console.log(sel_goods_attr);

    //-------------设置distAttrs 属性值-------------------------------------------

    for (let d = 0; d < distAttrs.length; d++) {
      //比对name 更改未选属性状态值
      for (let j = 0; j < other_notsel_attr.length; j++) {
        if (other_notsel_attr[j].name == distAttrs[d].name) {
          distAttrs[d] = other_notsel_attr[j];
        }
      }
      for (let s = 0; s < sel_goods_attr.length; s++) {
        if (sel_goods_attr[s].name == distAttrs[d].name) {
          distAttrs[d] = sel_goods_attr[s];
        }
      }
    }
    //更新属性值
    this.data.distAttrs = distAttrs;
    //--------------------拼接被选中属性值---------------------------
    let chooseIdStr = ''

    for (let i = 0; i < chooseAttrids.length; i++) {
      if (chooseAttrids[i] == undefined || chooseAttrids[i] == '') {
        continue;
      }
      if (chooseIdStr == '') {
        chooseIdStr = chooseAttrids[i];
      } else {
        chooseIdStr = chooseIdStr + ';' + chooseAttrids[i];
      }
    }

    // console.log('被选中属性值chooseIdStr---' + chooseIdStr);

    // 获取itemImg sku 小图；
    this.getSkuImg(chooseIdStr);
    //-----------------更改价格和库存--------------------------
    let hasSku = false; //是否存在skuid
    let product = this.data.product
    let sku_list = product.skus;
    for (let s = 0; s < sku_list.length; s++) {
      if (sku_list[s].attrListIds == chooseIdStr) {
        this.data.skuId = sku_list[s].id; //skuId
        this.data.itemId = sku_list[s].itemId; //交互---商品id
        this.data.count = 1;
        this.data.stock = sku_list[s].stock; //商品库存
        if (product.zjlimitdeprnPrice) { //有折扣商品取折扣价格（默认）
          this.data.itemPrice = sku_list[s].deprnPrices;
          this.data.limitedNum = sku_list[s].limitNum; //商品库存
          this.data.skuDeprnRatio = sku_list[s].deprnRatio || 0; //商品折扣
        } else {
          this.data.itemPrice = sku_list[s].price;
        }
        console.log('折扣数据', sku_list[s].deprnRatio, sku_list[s].limitNum);
        hasSku = true;
      }
    }
    if (!hasSku) {
      this.data.stock = product.stock; //商品库存
      this.data.skuId = ''; //商品skuid
      this.data.itemId = ''; //商品itemId
      this.data.itemPrice = ''; //商品显示价格
      this.data.skuDeprnRatio = 0; //商品折扣
    }
    // console.log("skuid:" + that.data.skuId);
    // console.log("itemId:" + that.data.itemId);
    // console.log("stock:" + that.data.stock);
    // console.log("count:" + that.data.count);
    // console.log("itemPrice:" + that.data.itemPrice);
    // console.log("itemImg:" + that.data.itemImg);

  },
  /**
   * 获取sku小图
   */
  getSkuImg: function(chooseAttrids) {
    let that = this;
    let product = that.data.product;
    let skuAttrs = product.skuAttrs;
    let findItemImg = false;
    console.log('获取sku小图');
    console.log('chooseAttrids--' + chooseAttrids);

    // 最小属性单位
    if (skuAttrs.length > 0) {
      for (let s = 0; s < skuAttrs.length; s++) {
        //判断带有小图的单位是否包含在已选属性id
        if (chooseAttrids.indexOf(skuAttrs[s].attrid) > -1) {
          console.log('skuAttrs[s].attrid--' + skuAttrs[s].attrid);
          console.log('找到匹配的sku小图' + skuAttrs[s].imgUrl);
          that.data.itemImg = skuAttrs[s].imgUrl;
          findItemImg = true;
          break;
        }
      }
      if (findItemImg === false) {
        that.data.itemImg = '';
      }
    }

  },
  //所有可能的路径
  //------------------获取所有包含指定节点的路线--------------------------
  filterProduct: function(chooseAttrids) { //ids
    let that = this;
    let allAttrids = []; //所有包含所选元素的节点路线
    //sku_list => sku
    let sku_list = this.data.product.skus;
    for (let s = 0; s < sku_list.length; s++) { //attrListIds
      if (sku_list[s].stock < 1) { //过滤掉库存小于1 的路线
        continue;
      }
      let attrListIds = ';' + sku_list[s].attrListIds + ';'
      let _all_ids_in = true;
      for (let c = 0; c < chooseAttrids.length; c++) {
        if (chooseAttrids[c] == "" || chooseAttrids[c] == undefined) {
          continue;
        }
        if (attrListIds.indexOf(';' + chooseAttrids[c] + ';') == -1) {
          _all_ids_in = false;
          break;
        }
      }
      if (_all_ids_in) {
        allAttrids.push(sku_list[s]); //所有符合条件的sku信息
      }
    }
    return allAttrids;
  },
  /**
   * 1. 获取 经过已选节点 所有线路上的全部节点
   * 2. 根据已经选择得属性值，得到余下还能选择的属性值
   */
  filterAttrs: function(chooseAttrids) {
    let that = this;
    // console.log('filterAttrs');
    let allAttrids = that.filterProduct(chooseAttrids); //所有符合条件的路线
    // console.log('所有符合条件的路线');
    // console.log(allAttrids);
    let result = [];
    for (let i = 0; i < allAttrids.length; i++) {
      result = result.concat(allAttrids[i].attrListIds.split(';'));
    }
    // console.log('所有符合条件的属性值array');
    // console.log(result);
    return result;
  },
  /**
   * 更改备选状态 (未选属性行元素，符合条件的所有属性值)
   */
  setBlock: function(goods_attr, all_ids) {

    let attrValue = goods_attr.value;
    for (let a = 0; a < attrValue.length; a++) {
      //查验符合条件的属性值是否包含（attrValue[a]）
      if (all_ids.indexOf(attrValue[a].id) == -1) { //没有
        attrValue[a].statu = 0;
      } else {
        if (attrValue[a].statu != 2) {
          attrValue[a].statu = 1;
        }
      }
    }
    return attrValue;
  },

  /**
   * 设置已选节点的同级节点是否可选(已选分组行元素，所有已选id)
   */
  update_2: function(goods_attr) {
    let that = this;
    let chooseAttrids = that.data.chooseAttrids;
    let attrValue = goods_attr.value;
    let changedValue = [];
    //找到被选中的元素值
    for (let a = 0; a < attrValue.length; a++) {
      if (attrValue[a].statu == 2) {
        /**
         * 剔除已选中元素的chooseAttrids
         */
        let chooseAttrids2 = that.del_array_val(chooseAttrids, attrValue[a].id);
        let all_ids = that.filterAttrs(chooseAttrids2); //筛选返回所有可选属性值
        changedValue = that.setBlock(goods_attr, all_ids);
      }
    }
    return changedValue;
  },
  /**
   * 把被选中的属性值从全部被选中数组中剔除并返回新数组
   */
  del_array_val: function(chooseAttrids, attrId) {
    let newArr = [];
    for (let c = 0; c < chooseAttrids.length; c++) {
      if (chooseAttrids[c] == undefined || chooseAttrids[c] == '') {
        continue;
      } else {
        if (chooseAttrids[c] != attrId) {
          newArr.push(chooseAttrids[c]);
        }
      }
    }
    return newArr;
  },
  addCount: function(e, that) { //增加商品数量

    let inputCount = e.target.dataset.count;
    let product = that.data.product;
    let count = that.data.count; //商品数量
    let stock = that.data.stock;
    let [isLimited, limitedNum] = [product.isLimited, that.data.limitedNum]; //限购数量

    let [msg, compareNum] = ['', 0]; //提示信息，比对数量

    //限购设置
    if (isLimited == '1' && stock > limitedNum && limitedNum > 0) { //库存和限购数量做对比 { //库存和限购数量做对比
      compareNum = limitedNum
      msg = '此商品为限购商品，限购数量为' + limitedNum
    } else {
      compareNum = stock
      msg = '库存不足';
    }

    //限购、库存不足提示
    if (inputCount < compareNum) {
      count = parseInt(inputCount) + 1
    } else { //大于等于商品库存数量
      count = compareNum
      util.showToast(msg, 1000, 'none', function() {});
    }

    this.data.count = count;
    this.data.stock = stock;
  },
  minsCount: function(e, that) {
    // console.log("minsCount:" + e);
    let appThis = this
    let inputCount = e.target.dataset.count;

    if (inputCount > 1) {
      appThis.data.count = parseInt(inputCount) - 1;
    } else {
      util.showToast('购买数量不能小于1', 1000, 'none', function() {});
      appThis.data.count = 1;
    }
  },
  changeCount: function(e, that) {
    let inputcount = e.detail.value;
    let stock = that.data.stock;
    let count = that.data.count;
    let product = that.data.product;
    console.log('inputcount', inputcount);
    //限购设置
    let [isLimited, limitedNum] = [product.isLimited, that.data.limitedNum]; //限购数量

    let [msg, compareNum] = ['', 0]; //提示信息，比对数量
    if (inputcount < 1) {
      msg = '购买数量不能小于1';
      count = 1;
    } else{
      //限购设置
      if (isLimited == '1' && stock > limitedNum && limitedNum > 0) { //库存和限购数量做对比
        compareNum = limitedNum
        msg = '此商品为限购商品，限购数量为' + limitedNum
      } else {
        compareNum = stock
        msg = '库存不足';
      }
    }
    //用户提示
    if (inputcount < 1){
      util.showToast(msg, 1000, 'none', function () { });
    }else{
      //限购、库存不足提示
      console.log('inputcount11', inputcount);
      if (inputcount < compareNum) {
        count = parseInt(inputcount);
      } else { //大于等于商品库存数量
        count = compareNum;
        util.showToast(msg, 1000, 'none', function () { });
      }
    }
    this.data.count = count;

  },
  validateSKU: function(that) { //验证sku
    let skus = that.data.product.skus;
    let distAttrs = that.data.distAttrs;
    let chooseAttrids = that.data.chooseAttrids; //已选商品id拼接
    let addcart = true; //是否满足条件 ---可以加入购物车

    //------------判断有无sku-------------------------------------
    if (skus.length > 0 && distAttrs.length > 0) {
      //----------------检查商品信息-------------------------------
      if (chooseAttrids.length > 0) {
        for (let i = 0; i < distAttrs.length; i++) {
          // console.log("chooseAttrids[i]" + chooseAttrids[i]);
          if (chooseAttrids[i] == '' || chooseAttrids[i] == undefined) {
            addcart = false;
            util.showToast("请选择 " + distAttrs[i].name, 1000, 'none', function() {});

            break;
          }
        }
      } else {
        util.showToast("请选择 " + distAttrs[0].name, 1000, 'none', function() {});
        addcart = false;
      }
    } else {
      addcart = true;
    }
    this.data.addcart = addcart;
    return addcart;
  },
  addCart: function(e, that) { //点击加入购物车
    //------------------------判断session是否过期-------------------------------

    let appThis = this;
    //-------------是否有推荐人--------------------------------
    // let inviter = that.data.inviter;
    let inviter = appThis.data.inviter;
    console.log('appThis.data.inviter分享人', appThis.data.inviter);
    //-------------验证判断------------------------------------
    let addType = e.target.dataset.type; //是否加入购物车 or 立即购买 add /submit
    let addcart = appThis.data.addcart //是否满足条件 ---可以加入购物车

    //-------------立即购买所需参数----------------------------
    let itemId = that.data.product.id; //商品id
    let skuId = that.data.skuId;
    let count = that.data.count; //加入购物车的数量
    let rdSession = wx.getStorageSync('rd_session');
    let zjGroupLevelId = that.data.zjGroupLevelId || ''; //拼团id

    console.log('that.data.orderInfo.id', that.data.orderInfo.id);
    //记录参团活动id;
    let zjGroupActivityId = that.data.orderInfo.id || '';
    appThis.data.zjGroupActivityId = zjGroupActivityId;

    let isAuthorization = appThis.data.isAuthorization;
    if (isAuthorization) {
      //店铺信息
      let [shopuid, shopInfo] = ['', wx.getStorageSync('shopInfo')];
      shopuid = shopInfo.shopuid || '';
      console.log('addcart:shopuid--' + shopuid);
      console.log('addcart:inviter--' + inviter);


      if (addcart) {

        //请求参数
        let data = {
          "itemId": itemId,
          "rdSession": rdSession,
          "skuId": skuId,
          "count": count,
          "inviter": inviter,
          "shopuid": shopuid,
          "zjGroupLevelId": zjGroupLevelId,
          "zjGroupActivityId": zjGroupActivityId
        };

        if (addType == 'add') {
          // console.log("skuid:" + skuId);
          // console.log("itemId:" + itemId);
          // console.log("count:" + appThis.data.count);
          //-------------向后台传递data----------------------------
          http.getReq('/weixin/cart/add', data, function(res) {
            // console.log('已加入购物车', res);
            if (res.ret) { //添加购物车成功
              util.showToast('已加入购物车', 500, 'none', function() {});
              appThis.getElementsCounts(); //查看购物车状态（购物车商品数量）
            } else { //加入购物车失败
              if (res.msg == 'SessionTimeOut') { //session失效
                // console.log('SessionTimeOut');
                appThis.SessionTimeOut();
              } else { //库存不足
                util.showToast(res.msg, 500, 'none', function() {});
              }
            }
            console.log("this.global.product:" + appThis.data.product);
          });

          appThis.data.count = 1;
        } else if (addType == 'submit') { //立即购买
          //-------------向后台传递data----------------------------
          console.log('skuId--' + skuId);
          http.getReq('/weixin/cart/ConverToProduct', data, function(res) {
            console.log('ConverToProduct', res);
            if (res.ret) {
              //-----返回的商品信息添加到cartProducts------
              let cartProducts = [];
              cartProducts.push(res.data);
              appThis.data.cartProducts = cartProducts;
              appThis.data.zjGroupLevelId = zjGroupLevelId; //团队阶级id
              wx.navigateTo({
                url: "/pages/product/pages/order/order",
              })
            } else {
              console.log('待付款订单跳转失败');
              //--------------重新登陆-----------------
              if (res.msg == "SessionTimeOut") {
                appThis.SessionTimeOut();
              }
            }
          });
        }
        if (e.target.dataset.type == 'submit') { //确认订单页
          appThis.data.toBuy = true
        } else {
          appThis.data.toBuy = false
        }

      } else {
        return;
      }
    } else {
      util.showToast('您还未登录,请先登录', 1000, 'none', function() {
        appThis.data.isAuthorization = false;
        appThis.loginAnimation();
        return;
      });
    }
  },

  cancelShare: function() { //取消分享
    console.log("取消分享")
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.height(0).step();
    this.data.animationData = animation.export();
    this.data.isshow = false;
  },

  toPayPage: function(that) { //待付款订单
    let appThis = this;
    let cartProducts = that.data.cartProducts; //待付款订单列表
    let totalCount = that.data.totalCount; //商品总额

    //过滤被选商品
    let newList = [];
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1) {
        newList.push(cartProducts[i]);
      }
    }
    appThis.data.cartProducts = newList;
    appThis.data.totalCount = totalCount;
    wx.navigateTo({
      url: '/pages/product/pages/order/order',
    })
  },

  //---------------------------------支付-----------------------------
  wxPay: function(e, that) { //提交订单

    let appThis = this;
    //-----判断是否有地址------------
    let [sendMessage, hasAddress] = [that.data.sendMessage, that.data.hasAddress]; //是否短信通知，是否有地址

    if (!hasAddress) {
      util.showToast('请新建收货地址', 1000, 'none', function() {});
      return;
    }

    //------设置支付按钮状态
    appThis.data.ispay = true;
    let formId = e.detail.formId; //formId用于发送模板消息
    let cartProducts = that.data.cartProducts; //待付款商品列表
    let rd_session = wx.getStorageSync('rd_session');
    let defaultAddress = that.data.defaultAddress; //默认地址
    let orderId = that.data.orderId; //判断订单是否有orderId
    let buyerMemo = that.data.buyerMemo; //买家留言
    let submitOrderNoPay = that.data.submitOrderNoPay; //只提交订单不支付
    let couponInfouserId = that.data.selectCoupon.couponInfouserId; //已选优惠券id
    let zjGroupLevelId = that.data.zjGroupLevelId; //拼团id
    let isGroupProduct = that.data.isGroupProduct; //是不是拼团订单
    //存formid用于发送模板推送消息
    if (submitOrderNoPay) {
      appThis.getFormId(e);
    }

    if (!appThis.checkDefaultAddress(defaultAddress)) {
      return
    }

    if (orderId == undefined || orderId == '' || orderId == null) { //没有订单调提交订单支付接口
      //提交表单
      appThis.submitOrder(cartProducts, rd_session, defaultAddress, formId, buyerMemo, submitOrderNoPay, couponInfouserId, zjGroupLevelId, isGroupProduct);
    } else { //有订单号
      appThis.payByOrderId(formId, orderId, rd_session, isGroupProduct)
    }
    //---------------根据订单是否支付成功发送模板消息---------------

  },
  /**
   * 检查省份信息
   */
  checkDefaultAddress: function(defaultAddress) {
    let pcc = defaultAddress.pcc.trim() == '省份' ? '' : defaultAddress.pcc;
    if (!pcc) {
      util.showToast('您的地址还有未完善的信息，请您检查地址后提交订单', 1500, 'none', '');
      return false
    } else {
      return true
    }
  },

  //提交订单
  submitOrder: function(cartProducts, rd_session, defaultAddress, formId, buyerMemo, submitOrderNoPay, couponInfouserId, zjGroupLevelId, isGroupProduct) {
    // console.log('submitorder表单id' + formId);
    let appThis = this;
    //店铺信息
    let [shopuid, shopInfo] = ['', wx.getStorageSync('shopInfo')];
    if (shopInfo.shopuid != undefined && shopInfo.shopuid != null && shopInfo.shopuid != '') {
      shopuid = shopInfo.shopuid;
    }
    //请求参数
    let productLevMsgs = appThis.data.productLevMsgs
    let data = {
      'productList': JSON.stringify(cartProducts),
      'rdSession': rd_session,
      'buyerAddress': JSON.stringify(defaultAddress),
      'shopuid': shopuid,
      'buyerMemo': buyerMemo,
      'couponInfouserId': couponInfouserId || '',
      'productLevMsgs': appThis.data.productLevMsgs.length > 0 ? JSON.stringify(appThis.data.productLevMsgs) : '', //自定义留言项、
      'zjGroupLevelId': zjGroupLevelId, //拼团id
      'zjGroupActivityId': appThis.data.zjGroupActivityId //拼团活动id
    };

    let msgImgObj = appThis.data.msgImgObj || {}; //留言项是否有需要上传图片的项目
    if (submitOrderNoPay) { //只提交订单不付款

      http.getReq('/weixin/order/submitOrderNoPay', data, function(res) {

        //需要上传留言图片
        if (msgImgObj.src) {
          appThis.uploadMsgImg(msgImgObj, res.data.orderId);
        }

        //重定向到全部订单
        setTimeout(function() {
          wx.redirectTo({
            url: '/pages/user/pages/orders/orders?activeIndex=1&statusOri=10', //跳转至待付款订单列表
          })
        }, 100)
      }, true, '取消支付中');

    } else {

      http.postReq('/weixin/order/submitOrder', data, function(res) {
        console.log('submitOrder', res);
        //需要上传留言图片
        if (msgImgObj.src) {
          appThis.uploadMsgImg(msgImgObj, res.data.orderId);
        }

        console.log("提交订单结果", res);
        let ret = res.ret;
        let [prepay_id, orderId] = ['', ''];
        if (ret) {

          prepay_id = res.data.prepay_id;
          orderId = res.data.orderId;

          //提交订单成功获取支付接口
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: 'MD5',
            paySign: res.data.paySign,
            success: function(res) {

              util.showToast('支付成功', 1000, 'success', function() {
                //修改订单状态 发送模板消息
                appThis.payCallBack(orderId, rd_session);
                //发送支付成功模板消息
                appThis.paySendTemp(true, formId, rd_session, orderId, isGroupProduct);

              });

            },
            fail: function(res) { //待付款订单 
              //修改（刷新）订单支付状态

              wx.redirectTo({
                url: '/pages/user/pages/orders/orders' //跳转到待付款订单列表
              })

              util.showToast('付款失败', 1000, 'none', function() {

                http.getReq('/weixin/order/payFail', {
                  orderId: orderId
                }, function(res) {

                  console.log("付款失败", res);
                  //支付失败的模板--待付款通知模板------------------------------------
                  // appThis.paySendTemp(false, formId, rd_session, orderId);
                }, true)

              });
            }
          })



        } else {
          let msg = res.msg
          if (msg !== 'reSubmit') {
            if (msg == '您不能加入该活动') {
              msg = '活动已结束，您不能加入该活动';
            } else {
              msg = '提交订单失败';
            }
            util.showToast(msg, 1000, 'none', function() {
              //重定向到全部订单
              setTimeout(function() {
                wx.redirectTo({
                  url: '/pages/user/pages/orders/orders',
                })
              }, 1200)
            });

          }
        }
        // 清空自定义留言信息
      }, true, '正在发起支付');
    }
  },
  //根据订单编号支付商品
  payByOrderId: function(formId, orderId, rd_session, isGroupProduct) {
    let appThis = this;
    let data = {
      'orderId': orderId,
      'rdSession': rd_session,
    }
    //支付订单----------------------------------------------------------
    http.getReq('/weixin/order/payOrder', data, function(res) {
      console.log('payOrder', res);
      if (res.ret) {
        //微信支付
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: 'MD5',
          paySign: res.data.paySign,
          success: function(res) {
            console.log("支付成功", res);
            //支付成功弹窗
            util.showToast('支付成功', 1500, 'success', '');
            //修改订单状态 发送模板消息
            appThis.payCallBack(orderId, rd_session);
            //发送支付成功模板消息
            appThis.paySendTemp(true, formId, rd_session, orderId, isGroupProduct);

          },
          fail: function(res) { //待付款订单
            //修改（刷新）订单支付状态
            wx.redirectTo({
              url: '/pages/user/pages/orders/orders',
            })

            util.showToast('付款失败', 1000, 'none', function() {

              http.getReq('/weixin/order/payFail', { //用户没有支付
                orderId: orderId
              }, function(res) {
                //支付失败的模板--待付款通知模板------------------------------------
                // appThis.paySendTemp(false, formId, rd_session, orderId);
                console.log("付款失败", res);
              })

            });

          },

        })
      } else {
        let msg = res.msg;
        if (msg == '您不能加入该活动') {
          msg = '活动已结束，您不能加入该活动';
        } else {
          msg = '提交订单失败';
        }
        util.showToast(msg, 1000, 'none', function() {
          //重定向到全部订单
          setTimeout(function() {
            wx.redirectTo({
              url: '/pages/user/pages/orders/orders',
            })
          }, 1000)
        });
      }



    });

  },
  backToHome: function(that) { //返回到首页
    //回到首页
    wx.switchTab({
      url: '/pages/home/home', //店铺id 、店铺名称 、分享标识
      success: function(e) { //跳转刷新
        let page = getCurrentPages().pop(); //强制刷新跳转页面，
        if (page == undefined || page == null) return;

      }
    })
  },
  //根据商品id跳转至商品详情页
  selectProductById: function(that) {
    let shopInfo = wx.getStorageSync('shopInfo');
    let shopuid = that.data.shopuid;
    if (shopInfo.shopuid) {
      shopuid = shopInfo.shopuid;
    }
    console.log('?productId=' + that.data.productId + '&shopuid=' + shopuid);
    wx.navigateTo({
      url: that.data.pageUrl + '?productId=' + that.data.productId + '&shopuid=' + shopuid,
      success: function(res) {
        wx.hideToast();
      }
    })
  },
  //----------播放弹窗动画、遮罩层-------------------------
  makeAnimation: function() {
    let that = this;
    //初始化动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    // animation.translateY('100%').step()
    animation.translateY('100%').step()
    that.data.animationData = animation.export();
    that.data.opMask = 1;
    that.data.isshow = true;
    setTimeout(function() {
      animation.translateY(0).step()
      that.data.animationData = animation.export();
    }.bind(this), 50)
    //通过动画实例得export方法导出动画数据给自身得animation属性
    //调用一次export 方法后也会清除到之前得动画操作
  },
  cancelAnimation: function() { //收回弹窗、隐藏遮罩层
    let that = this;
    //初始化动画
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.translateY('100%').step();
    that.data.animationData = animation.export();

    setTimeout(function() {
      animation.translateY(0).step();
      that.data.animationData = animation.export();
      that.data.isshow = false;
      that.data.showLogin = false;
    }.bind(this), 200)

    //通过动画实例得export方法导出动画数据给自身得animation属性
    //调用一次export 方法后也会清除到之前得动画操作
  },
  toCategoryPage: function(e) {
    let catyindex = e.currentTarget.dataset.catyindex;
    wx.navigateTo({
      url: '/pages/home/pages/category/category?catyindex=' + catyindex
    })
  },


  //----------------验证绑定手机号表单--------------------

  //手机预览商品缩略图
  previewImage: function(e) {
    let codeUrl = e.currentTarget.dataset.src;
    let scanQrCodeUrl = []
    scanQrCodeUrl.push(codeUrl);
    wx.previewImage({
      urls: scanQrCodeUrl,
    })
  },
  //设置店铺信息：
  setShopTitle: function() {

    //获取本地的店铺信息------------------------------------------
    let shopInfo = wx.getStorageSync('shopInfo');
    console.log('设置店铺标题：', shopInfo);
    //设置店铺标题：
    // if (shopInfo.shopName) {
    wx.setNavigationBarTitle({ //设置首页店铺名称显示
      title: '咱 + ' + (shopInfo.shopName ? shopInfo.shopName : '')
    })
  },

  //------------------未开通服务提示----------------------
  unOpen: function() {
    util.showToast('该功能尚未开通，敬请期待~', 1500, 'none', function() {});
  },
  //--------------------消息提示----------------------------
  connectionTimeout: function(msg, time) {
    let defaultMsg = '网络异常，请稍后再试';
    util.showToast(msg || defaultMsg, time || 1500, 'none', function() {});
  },
  //图片加载失败出现错误时替换图片路径
  errImg: function(products, proIndex) {
    // console.log('修改成默认图片－－－');
    // console.log(typeof products[proIndex].thumbImgs, typeof products[proIndex].itemimags);
    if (products[proIndex].thumbImgs != undefined) {
      console.log('修改成默认图片');
      products[proIndex].thumbImgs = this.data.defaultImgUrl; //修改成默认图片
    }
    if (products[proIndex].itemimags != null) {
      products[proIndex].itemimags[0].thumbImgs = this.data.defaultImgUrl; //修改成默认图片
    }
    return products;
  },
  //获取formid
  getFormId: function(e) {
    let formId = e.detail.formId;
    if (formId != 'the formId is a mock one' && formId != '') {
      let formObj = {};
      formObj.formId = formId;
      formObj.expiryTime = parseInt(new Date().getTime() / 1000) + 604800; //计算7天后的过期时间时间戳;
      this.data.formIdPool.push(formObj);
    }
    console.log('formIdPool:' + this.data.formIdPool);
  },

  //获取用户绑定的真实姓名
  getUserName: function() {
    // console.log('获取用户绑定的真实姓名');
    let that = this;
    let rdSession = wx.getStorageSync('rd_session');

    http.getReq("/weixin/withdraw/getRealName", {
      rdSession: rdSession
    }, function(res) {

      console.log('获取用户绑定的真实姓名getUserName', res);
      let hasRealName = res.data.hasRealName; //true/false
      let userName = '';
      if (hasRealName) {
        userName = res.data.realName;
      }
      that.data.hasRealName = hasRealName; //用户是否绑定真实姓名
      that.data.userName = userName; //用户真实姓名
    });
  },
  //设置用户授权状态
  setUserInfoScope: function(pageData) {
    this.data.isAuthorization = pageData.data.userInfoScope; //用户信息授权
  },
  //设置地理位置信息
  setCityName: function(cityName) {
    this.data.cityName = cityName || '北京';
    wx.setStorageSync("cityName", cityName || '北京'); //保存到本地
  },
  //加载城市列表
  loadCityArray: function() {
    let that = this;
    let cityName = that.data.cityName;
    if (cityName != '成都') { //成都不需要加载城市列表
      http.getReq('/weixin/sys/ZjCity/list', {}, function(res) {
        console.log('返回加载城市列表:', res);
        that.data.cityArray = res;
      });
    }
  },
  /**
   * 保存formid
   */
  saveFormIdPool: function() {
    let that = this;
    //发送存储formIdPool
    let formIdPool = that.data.formIdPool;
    let rdSession = wx.getStorageSync('rd_session');

    if (formIdPool.length > 0) {
      //回调中清空本地formIdPool
      http.getReq('/weixin/formid/save', {
        rdSession: rdSession,
        formIdPool: formIdPool
      }, function(res) {
        console.log("saveFormIdPool", res);
        that.data.formIdPool = [];
      });
    }
  },
  //
  /**
   * 改变选择城市
   */
  onCityChange: function(e) {
    let that = this;
    let [cityArray, index] = [that.data.cityArray, e.detail.value];
    that.data.cityName = cityArray[index];
  },

  getDiscountCard: function() { //获取用户优惠券列表
    let that = this;
    http.getReq('/weixin/couponInfo/list', {
      rdSession: wx.getStorageSync('rd_session')
    }, function(res) {
      console.log('优惠券信息', res);
      if (res.ret) { //优惠券
        that.data.discountCardList = res.data;
      }
    });
  },
  cancelSettingBox: function() { //关闭设置提示窗
    this.data.showSettingBox = false;
  },
  showSettingBox: function() { //打开设置提示窗
    this.data.showSettingBox = true;
  },
  //发送支付模板消息
  paySendTemp: function(ret, formId, rd_session, orderId, isGroupProduct) {

    let [template_id, page, requestUrl] = ['', '', ''];
    //支付是否成功
    if (ret) {
      template_id = 'vozG3chDxaKJ4cOnzr2LZAhXwgZF4mQ4XM_6DsNfXow'; //  'W3WizWfcMElByn9iRKpiY8t7fFkxyl9opBLUSOiN5ng'; //  
      page = 'pages/home/home?paySendTemp=1'; //小程序点击发送模板消息进入
      requestUrl = '/weixin/msg/payOkSend';
    } else {
      template_id = 'lePzgGRMbxNu8qKatPL7S1Fm3LmwG0-mUPq3NjpybMU'; // '80woXa3XellcOG2096S6E7k_DyFKi--9ApMubORtNf0'; // 
      page = 'pages/product/order/order?orderId=' + orderId; //跳转到待付款订单页面
      requestUrl = '/weixin/msg/payFailSend';
    }

    let data = {
      form_id: formId,
      rdSession: rd_session,
      template_id: template_id,
      page: page, //跳转到全部订单页面 
      orderId: orderId
    }

    http.getReq(requestUrl, data, function(res) { //回调
      //--------------------支付成功/失败后的跳转---------------------------------
      let navUrl = ''; //跳转路径

      if (ret) {
        if (isGroupProduct == '1') {
          navUrl = '/pages/product/pages/pinShareOrder/pinShareOrder?orderId=' + orderId; //跳转到全部
        } else {
          navUrl = '/pages/user/pages/orders/orders'; //跳转到待付款订单列表
        }
        console.log('发送模板消息成功');
      } else {
        navUrl = '/pages/user/pages/orders/orders?activeIndex=1&statusOri=10'; //跳转到待付款订单列表
      }
      wx.redirectTo({
        url: navUrl
      })

    }, true, '正在加载订单');

  },
  //修改订单状态
  payCallBack: function(orderId, rd_session) {
    http.getReq('/weixin/order/payCallBack', {
      'orderId': orderId,
      'rdSession': rd_session
    }, function(res) {
      console.log('修改订单状态', res);
    });
  },
  //获取最大最小价格
  getNewList: function(itemList) { //获取最大最小价格
    if (itemList.length > 0) {
      for (let p = 0; p < itemList.length; p++) {
        let skus = itemList[p].skus;
        if (skus.length > 0) {
          let skuPrices = [];
          for (let s = 0; s < skus.length; s++) {
            skuPrices.push(skus[s].price);
          }

          itemList[p].minPrice = Math.min(...skuPrices);
          itemList[p].maxPrice = Math.max(...skuPrices);
        }
      }
      this.data.itemList = itemList;
    }
  },
  //登录过期 返回首页登录
  SessionTimeOut: function() {
    Util.showToast('您的登录已过期，请重新登录', 1500, 'none', () => {
      this.data.SessionTimeOut = true;
      setTimeout(this.backToHome, 1500)
    })
  },
  /**
   * 获取分享店铺信息
   */
  getShareShopInfo: function(shopuid, inviter) {
    let that = this;
    //店铺和分享人信息
    shopuid = shopuid || '';
    inviter = inviter || '';
    http.getReq('/weixin/getShopInviter', {
      shopuid: shopuid,
      inviter: inviter,
      rdSession: wx.getStorageSync('rd_session') || ''
    }, function(res) {
      console.log('setShopInfo 返回信息', res);

      let shopInfo = {};
      if (res.data.shopuid) { //根据分享携带信息查询到店铺
        shopInfo.shopuid = res.data.shopuid; //店铺id
        shopInfo.shopName = res.data.shopName; //店铺名称
        shopInfo.isOwnShop = ''; //是否为自己的店铺
        wx.setStorageSync('shopInfo', shopInfo); //当前本地店铺信息
        that.data.hasGotShopInfo = true;
      } else {
        that.data.hasGotShopInfo = false;
      }


    });
  },
  /**
   * 错误收集
   */
  onError: function(err) {
    console.log('onError上报错误:', err);
    console.log('报错用户uid,shopuid,inviter,username，time')
  },
  //店铺过期，清理店铺
  clearShopInfo: function() {
    let that = this;

    //没个一段时间检查店铺是否过期
    checkShopInfoTask = setTimeout(function() {
      console.log('clearShopInfo开始清除分享店铺信息，回到初始关注店铺');
      that.data.shopInfoTimeOut = true;
      // //清除店铺以及分享人信息
      that.data.shopuid = '';
      that.data.inviter = '';
    }, that.data.shopInfoExTime)

  },
  //恢复店铺过期初始值
  recoverShopInfoTime: function() {
    this.data.shopInfoTimeOut = false;
  },
  /**
   * 检查有无店铺优惠券
   */
  checkShopCoupon: function(shareKey, rd_session = wx.getStorageSync('rd_session')) {
    let checkShopCouponTask = setInterval(() => {
      let isAuthorization = this.data.isAuthorization;
      let cityName = this.data.cityName;

      if (isAuthorization === true && cityName !== '') {
        clearInterval(checkShopCouponTask);
        http.getReq('/weixin/wxUser/checkHasShopCoupon', {
          rdSession: rd_session,
          shareKey: shareKey
        }, (res) => {
          console.log('checkShopCoupon', res);
          this.data.hasShopCoupon = res.data.hasShopCoupon; //'0':没有 '1':有
        })
      }
    }, 1000);

  },
  /**
   * 获取待付款订单优惠券信息
   */
  getShopCoupon: function(total) {
    http.getReq('/weixin/couponInfo/wholePlaceCouponList', {
      rdSession: wx.getStorageSync('rd_session'),
      total: total
    }, (res) => {
      console.log('getShopCoupon', res);
      this.data.hasCouponInfo = res.ret;
      this.data.couponInfo = res.data; //优惠券信息
    })
  },
  //清空已选优惠券信息
  clearSelectCoupon: function() {
    this.data.selectCoupon = '';
  },
  //选择使用的优惠券
  saveSelectCoupon: function(selectCoupon) {
    this.data.selectCoupon = selectCoupon || '';
  },
  //清空自定义留言信息
  clearProductLevMsgs: function() {
    this.data.productLevMsgs = '';
    this.data.msgImgObj = '';
  },
  // 自定义消息保存到本地
  saveProductLevMsgs: function(productLevMsgs, msgImgObj) {
    this.data.productLevMsgs = productLevMsgs;
    this.data.msgImgObj = msgImgObj;
  },
  // 上传留言图片
  uploadMsgImg: function(msgImgObj, orderId) {
    wx.uploadFile({
      url: this.data.baseUrl + '/weixin/zjOrderMessage/upImg', //仅为示例，非真实的接口地址
      filePath: msgImgObj.src || '',
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      formData: {
        'zjItemMessageId': msgImgObj.id || '',
        'orderId': orderId || ''
      },
      success(res) {
        console.log('上传图片成功', res);
      }
    })
  },
  /**
   * 将留言类型从中文转化成英文
   */
  getLevMsgType: function(val) {
    switch (val) {
      case '单行文本':
        return 'text' //input
        break;
      case '图片':
        return 'image' //view image
        break;
      case '多行文本':
        return 'text' //textarea
        break;
      case '手机号':
        return 'number' //input
        break;
      case '数字格式':
        return 'digit' //input
        break;
      case '日期':
        return 'date' //picker
        break;
      case '日期时间':
        return 'datetime'
        break;
      case '时间':
        return 'time'
        break;
      case '身份证号':
        return 'idcard' //input
        break;
      case '邮件':
        return 'email'
        break;

    }
  },
  /**
   * 是否关注过咱加
   */
  checkIsFollowUser: function(rd_session) {
    http.getReq('/weixin/getIsFollowChat', {
      rdSession: rd_session
    }, (res) => {
      console.log('checkIsFollowUser', res);
      this.data.isFollowChat = res.data.isFollowChat;
    })
  },
  /**
   * 定时任务  显示添加到我的小程序
   */
  showCollectionTip:function(){
    this.data.showCollectionTip = true; //初始化显示添加小程序标签
    setTimeout(()=>{
      this.data.showCollectionTip = false; //初始化显示添加小程序标签
    },30000)
    
  }
})